package com.jsu.clubmanagementsystem.controller.club;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.club.ClubDeleteRequest;
import com.jsu.clubmanagementsystem.model.dto.club.ClubQueryRequest;
import com.jsu.clubmanagementsystem.model.dto.clubmembership.ClubMemberQueryRequest;
import com.jsu.clubmanagementsystem.model.entity.*;
import com.jsu.clubmanagementsystem.model.vo.club.ClubMembershipVO;
import com.jsu.clubmanagementsystem.model.vo.club.ClubTypeVO;
import com.jsu.clubmanagementsystem.model.vo.club.ClubVO;
import com.jsu.clubmanagementsystem.model.vo.club.ListClubVO;
import com.jsu.clubmanagementsystem.service.club.ClubMembershipService;
import com.jsu.clubmanagementsystem.service.club.ClubService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/club")
public class ClubController {

    @Resource
    private ClubService clubService;

    @Resource
    private ClubMembershipService clubMembershipService;

    @Resource
    private UserService userService;

    /**
     * 查找社团封装
     *
     * @param clubId
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ClubVO> getClubVoById(long clubId, HttpServletRequest request) {
        if (clubId <= 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数不合法");
        }
        User loginUser = userService.getLoginUser(request);

        Club club = clubService.getById(clubId);
        if (club == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标社团不存在");
        }
        ClubVO clubVO = clubService.getClubVO(club);
        return ResultUtils.success(clubVO);
    }

    /**
     * 查找社团封装 (分页）
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/vo")
    public BaseResponse<Page<ClubVO>> listClubVoByPage(@RequestBody ClubQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        //1. 获取QueryWrapper
        QueryWrapper<Club> queryWrapper = clubService.getQueryWrapper(queryRequest);
        //2. 处理Page
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        Page<Club> page = clubService.page(new Page<>(current, pageSize), queryWrapper);
        Page<ClubVO> voPage = clubService.getClubVoPage(page);
        return ResultUtils.success(voPage);
    }

    /**
     * 查看用户加入的社团列表
     *
     * @param queryRequest 查询请求
     * @param request      HTTP请求
     * @return 社团分页数据
     */
    @PostMapping("/list/club")
    public BaseResponse<Page<ClubMembershipVO>> listClubVoOfUserByPage(@RequestBody ClubMemberQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        Long userId = queryRequest.getUserId();
        User loginUser = userService.getLoginUser(request);
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        } else if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)) {
            if (!userId.equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH, "非用户本人，无法查询");
            }
        }

        Page<ClubMembershipVO> clubMembershipVOPage = clubService.listClubMembershipVoOfUserByPage(queryRequest);
        return ResultUtils.success(clubMembershipVOPage);
    }

    /**
     * 查看社团成员表 (数据脱敏)
     *
     * @param queryRequest 查询请求
     * @param request      HTTP请求
     * @return 成员分页数据
     */
    @PostMapping("/list/user")
    public BaseResponse<Page<ClubMembershipVO>> listUserVoInClubByPage(@RequestBody ClubMemberQueryRequest queryRequest, HttpServletRequest request) {
        Long clubId = queryRequest.getClubId();
        if (queryRequest == null || clubId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN) &&
                !clubMembershipService.isMemberOfClub(loginUser.getId(), clubId)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "非该社团成员，无法查看");
        }

        Page<ClubMembershipVO> page = clubService.listClubMembershipVoOfClubByPage(queryRequest);
        return ResultUtils.success(page);
    }

    /**
     * 判断用户是否是该社团的成员
     *
     * @param queryRequest
     * @return
     */
    @PostMapping("/is-member")
    public BaseResponse<Boolean> isMemberOfClub(@RequestBody ClubMemberQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        Long userId = queryRequest.getUserId();
        Long clubId = queryRequest.getClubId();
        if (!userService.isExist(userId) || !clubService.isExist(clubId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户或目标社团不存在");
        }
        return ResultUtils.success(clubMembershipService.isMemberOfClub(userId, clubId));
    }

    /**
     * 获取社团列表（管理员）
     */
    @PostMapping("/list/all")
    public BaseResponse<Page<ListClubVO>> getAllClub(@RequestBody PageQueryRequest page){
        return ResultUtils.success(clubService.getAllClub(page));
    }

    /**
     * 获取社团类型（管理员
     * @return
     */
    @GetMapping("/type")
    public BaseResponse<ClubTypeVO> gettype(){
        return ResultUtils.success(clubService.getClubType());
    }

    /**
     * 删除社团(包括批量删除社团)
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteClub(@RequestBody List<ClubDeleteRequest> clubs){
        return ResultUtils.success(clubService.deleteClubs(clubs));
    }
    @GetMapping("/get/activity/{userId}")
    public BaseResponse<List<Activity>> getActivityInClub(@PathVariable Long userId){
        return ResultUtils.success(clubService.getActivityInClub(userId));
    }

    @GetMapping("/get/announcement/{clubId}")
    public BaseResponse<List<ClubAnnouncement>> getAnnouncementInClub(@PathVariable Long clubId){
        return ResultUtils.success(clubService.getClubAnnouncementList(clubId));
    }
}
